<!--引入thymeleaf模板引擎-->
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head id="ctl00_head1">
    <meta http-equiv="x-ua-compatible" content="IE=7"/>
    <title>show</title>
    <meta charset="utf-8">
    <link href="/home/css/style.css" rel="stylesheet" type="text/css"/>
    <link href="/home/css/common.css" rel="stylesheet" type="text/css"/>
    <link rel="stylesheet" type="text/css" href="/home/css/hzw-city-picker.css">
    <link rel="stylesheet" type="text/css" href='/home/css/showcss/search.css'/>
    <!--<link rel="stylesheet" type="text/css" href="/home/css/showcss/hf.css"/>-->
    <link rel="stylesheet" type="text/css" href="/home/css/reset1.css"/>
    <link rel="stylesheet" type="text/css" href="/home/css/style1.css"/>
    <link rel="stylesheet" type="text/css" href="/home/css/button.css">
    <link rel="stylesheet" type="text/css" href="/home/css/show.css">

    <!-- 引入本地Vue.js -->
    <script type="text/javascript" src="/home/js/vue.js"></script>
    <!-- 引入本地Axios -->
    <script type="text/javascript" src="/home/js/axios.js"></script>
    <script type="text/javascript" src="/home/js/config.js"></script>
    <script type='text/javascript' src='/home/js/cQuery_110421.js'></script>
    <script type='text/javascript' src='/home/js/float.min.js'></script>
    <script type="text/javascript" src="/home/js/jquery-1.9.1.min.js"></script>

    <style>
        .up-box {
            border: 1px solid #ccc;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
            background-color: #ffffff; /* 设置背景颜色 */
            opacity: 1; /* 设置不透明度 */
        }

        .up-box-hd {
            padding: 10px;
            text-align: center;
        }

        /* 经停站浮窗样式 */
        .stations-popup {
            position: absolute;
            top: 100%;
            left: 0;
            margin-top: 10px;
            width: 300px;
            background: white;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            padding: 0;
            font-size: 14px;
        }

        .station-index {
            display: inline-block;
            width: 24px;
            height: 24px;
            line-height: 24px;
            text-align: center;
            background: #009f95;
            color: white;
            border-radius: 50%;
            margin-right: 10px;
            font-size: 12px;
        }

        .station-time-info {
            margin-top: 5px;
            font-size: 12px;
            color: #666;
        }

        .time-label {
            margin-right: 5px;
            color: #999;
        }

        .stations-header {
            background: #f5f5f5;
            padding: 10px 15px;
            border-bottom: 1px solid #ddd;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .stations-header h3 {
            margin: 0;
            font-size: 16px;
            color: #333;
        }

        .stations-close {
            font-size: 20px;
            color: #999;
            cursor: pointer;
            line-height: 1;
            padding: 0 5px;
        }

        .stations-close:hover {
            color: #333;
        }

        .stations-content {
            max-height: 300px;
            overflow-y: auto;
            padding: 10px 0;
        }

        .station-list {
            padding: 0 15px;
        }

        .station-item {
            position: relative;
            padding: 8px 0;
        }

        .station-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;
            z-index: 2;
            background: white;
            padding: 0 5px;
        }

        .station-name {
            font-weight: 500;
            color: #333;
        }

        .station-time {
            color: #666;
            font-size: 12px;
        }

        .station-connector {
            position: absolute;
            top: 30px;
            left: 20px;
            width: 2px;
            height: 20px;
            background: #ddd;
            z-index: 1;
        }

        .no-stations {
            text-align: center;
            color: #999;
            padding: 20px;
        }

        /* 调整车次信息的鼠标悬浮样式 */
        .checi:hover h1 {
            color: #1e90ff;
            color: white;
            background-color: #3b99fc;
            position: relative; /* 为关闭按钮定位 */
        }

        /* 点击选中的车次样式 */
        .checi.selected h1 {
            color: #1e90ff;
            font-weight: bold;
        }

        .up-box-hd .close-btn {
            position: absolute;
            top: 50%;
            right: 10px;
            transform: translateY(-50%);
            cursor: pointer;
            color: white;
            font-size: 18px;
        }

        .up-box-bd {
            padding: 10px;
            overflow-y: auto;
        }

        /* 日期选择器选中样式 */
        #ulCanlender02 ul li a.current {
            background-color: #3480e2;
            color: #fff;
            border-radius: 4px;
            font-weight: bold;
            display: block;
            padding: 8px 5px;
            text-align: center;
            width: 100%;
            box-sizing: border-box;
            line-height: 1.2;
        }

        .stations-container {
            display: flex;
            align-items: center;
            justify-content: space-around;
            flex-wrap: wrap;
            gap: 10px;
        }

        .station {
            display: flex;
            align-items: center;
            gap: 5px;
            padding: 5px 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            background-color: #f9f9f9;
        }

        .arrow::before {
            content: ">";
            font-weight: bold;
        }

        .station-text {
            font-size: 14px;
            font-weight: bold;
        }

        /* 用于遮盖最后一个站点前的箭头 */
        .last-station .arrow::before {
            content: "";
        }

        /* 遮罩层 */
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色 */
            z-index: 19999; /* 确保遮罩层在弹窗之下 */
            display: none;
        }
    </style>
</head>
<body id='mainbody'>
<div id="app">
    <!--引入header.html文件-->
    <div id="header"></div>
    <div style="position: absolute;top:292px;left:1723px;z-index:1000;background-color: #fff;width: 20px;height: 20px;"></div>
    <div id="main">
        <!--==搜索框==-->
        <div class="base_bd">
            <div class="search_box" style="margin-top: 10px;height: 25px">
                <form id="form" v-on:submit.prevent="changeValue">
                    <ul>
                        <input type="hidden" id="timeChangeFlag" name="changeFlag" :value="changeFlag">
                        <input type="hidden" id="timeChangeFlag_num" name="changeFlag_num" :value="changeFlag_num">

                        <!--出发地-->
                        <li class="search_region_lft">
                            <input type="text" name="start_station" v-model="startCity" readonly
                                   style="margin: -7px -11px -55px; height: 23px; width: 130px;" placeholder="出发地">
                        </li>
                        <li class="search_exchanged">
                            <a class="exchangedBtn" id="change1" style="margin-left: 25px"
                               @click="exchangeCities">换</a>
                        </li>
                        <!--目的地-->
                        <li class="search_region_rit" bus="true">
                            <input type="text" name="end_station" v-model="endCity" readonly placeholder="目的地"
                                   style="margin: -5px 0px 0px -24px; width: 127px; height: 22px;">
                        </li>
                        <li class="search_date_lft" style="margin-left: 20px">出发日期</li>
                        <li class="search_dateInput_lft">
                            <input type="hidden" id="time1" name="go_time" v-model="goTime">
                            <input class="txt100" id="ECalendar_case1" v-model="displayDate"
                                   style="margin: -5px 0px 0px -15px;width: 118px; cursor: pointer;" readonly
                                   @click="showDatePicker">
                        </li>
                        <li class="search_Btn">
                            <input style="background: #fb7403; width: 80px;height: 30px;margin: -20px 0px;"
                                   class="blueBtn" value="查询" type="submit">
                        </li>
                    </ul>
                </form>
            </div>
            <input type="hidden" id="from" v-model="from"/>
            <input type="hidden" id="to" v-model="to"/>
            <input type="hidden" id="tos" v-model="tos"/>
            <input type="hidden" id="hub" v-model="hub"/>
            <input type="text" id="validates" v-model="validates" style="display: none"/>
        </div>

        <!--==车次信息==-->
        <div class="base_bd">
            <div class="trainList_box">
                <!--查询到的车次信息-->
                <div class="trainList_title" style="width: 1200px">
                    <h2>
                        <strong>{{ startCity }}</strong> <i class="arr"></i> <strong>{{ endCity }}</strong>
                    </h2>
                    <span style="font-size: 14px">({{ goTime }})</span>
                    <b id="titleResult">（共计
                        <a style="color: #333;" id="totalResult">{{ trainList.length }}</a> 个车次）
                    </b>
                    <!-- 当前时间 -->
                    <b id="current-time">{{ currentTime }}</b>
                </div>
                <!--横排日期选择-->
                <div class="calendar" id="ulCanlender02">
                    <div class="cal_left">
                        <a class="icon_cal_left" @click="CanlenderLeftButtonClick"><i></i></a>
                    </div>
                    <ul class="cal_middle1" id="centerUlList1">
                        <li v-for="(date, index) in dateList" :key="index">
                            <a class="" style="cursor: pointer;" :class="{current: index === currentDateIndex}"
                               @click="selectDate(index)">
                                {{ date.date }}<br>{{ date.day }}
                            </a>
                        </li>
                    </ul>
                    <div class="cal_right">
                        <a class="icon_cal_right" @click="CanlenderRightButtonClick"><i></i></a>
                    </div>
                </div>

                <!--车次信息表头-->
                <div id="listheader" style="width: 1162px;">
                    <dl class="topic_box">
                        <dd class="w1">
                            <label style="cursor: default;margin-left: 18px">车次信息</label>
                        </dd>
                        <dd class="w2">
                            <label class="icon_blue_down sort" order='1,default,false'>出发/到达时间
                                <b class="on"></b></label>
                        </dd>
                        <dd class="w3">
                            <label style="cursor: default">出发/到达站</label>
                        </dd>
                        <dd class="w4">
                            <label class="icon_gray_down sort" order="3,default,false">运行时长
                                <b class="on"></b></label>
                        </dd>
                        <dd class="w5">
                            <label class="icon_gray_down sort" order="8,default,false" style="margin-left: 44px;">参考价
                                <b class="on"></b></label>
                        </dd>

                        <dd class="w6">
                            <label order="8,default,false">剩余票数<b class="on"></b></label>
                        </dd>

                        <dd class="w7">
                            <label order="8,default,false">票务预定<b class="on"></b></label>
                        </dd>
                    </dl>
                </div>
            </div>
        </div>

        <div>
            <!--车次信息详情（遍历循环）-->
            <div class="banci" v-for="train in groupedTrainList" :key="train.trainNumberId" style="padding: 0%;">
                <!-- 车次基本信息行 - 同一行显示所有席别 -->
                <div style="display: flex; align-items: center; padding: 10px 0; border-top: 1px solid #eee;">
                    <!-- 第一列：车次信息 -->
                    <div class="w1">
                        <div class="checi" @click="toggleStations(train)"
                             style="position: relative; cursor: pointer;">
                            <h1 style="font-size: 20px;">{{ train.trainNumberId }}</h1>
                            <!-- 经停站浮窗 -->
                            <div v-if="clickedTrain && clickedTrain.trainNumberId === train.trainNumberId"
                                 class="stations-popup">
                                <div class="stations-header">
                                    <h3>{{ train.trainNumberId }} 经停站信息</h3>
                                    <span class="stations-close" @click.stop="closeStations">&times;</span>
                                </div>
                                <div class="stations-content">
                                    <div v-if="clickedTrain && clickedTrain.stations && clickedTrain.stations.length > 0"
                                         class="station-list">
                                        <div v-for="(station, index) in clickedTrain.stations"
                                             :key="station.id || index" class="station-item">
                                            <div class="station-info">
                                                <span class="station-index">{{ station.stationOrder }}</span>
                                                <span class="station-name">{{ station.stationName }}</span>
                                                <div class="station-time-info">
                                    <!-- 第一个站（始发站）只显示发车时间 -->
                                    <div v-if="index === 0 && station.departureTime">
                                        <span class="time-label">发车:</span>
                                        <span class="station-time">{{ formatDateTime(station.departureTime) }}</span>
                                    </div>
                                    <!-- 最后一个站（终点站）只显示到达时间 -->
                                    <div v-else-if="index === clickedTrain.stations.length - 1">
                                        <span class="time-label">到达:</span>
                                        <!-- 直接显示原始时间数据，添加调试信息 -->
                                        <span class="station-time">{{  formatDateTime(station.arriveTime) || '暂无时间数据' }}</span>
                                        <!-- 调试信息，将在页面显示原始的时间字段内容 -->
                                    </div>
                                    <!-- 中间站显示到达和发车时间 -->
                                    <div v-else>
                                        <div v-if="station.arriveTime">
                                            <span class="time-label">到达:</span>
                                            <span class="station-time">{{ formatDateTime(station.arriveTime) }}</span>
                                        </div>
                                        <div v-if="station.departureTime">
                                            <span class="time-label">发车:</span>
                                            <span class="station-time">{{ formatDateTime(station.departureTime) }}</span>
                                        </div>
                                    </div>
                                                </div>
                                            </div>
                                            <div v-if="index < clickedTrain.stations.length - 1"
                                                 class="station-connector"></div>
                                        </div>
                                    </div>
                                    <div v-else class="no-stations">加载经停站信息中...</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 第二列：出发/到达时间 -->
                    <div class="w2" style="margin-left: -50px;">
                        <div class="shijian"><h1 class="banciname">{{ formatDateTime(train.departureTime) }}</h1><span>{{ formatDateTime(train.arrivalTime)
                            }}</span></div>
                    </div>

                    <!-- 第三列：出发/到达站 -->
                    <div class="w3">
                        <div class="zhandian">
                            <h1 class="banciname"><i class="shi_icon">始</i>&nbsp;&nbsp;&nbsp;<font>{{ startCity
                                }}</font></h1>
                            <span><i class="zhong_icon">终</i>&nbsp;&nbsp;&nbsp;<font>{{ endCity }}</font></span>
                        </div>
                    </div>

                    <!-- 第四列：运行时长 -->
                    <div class="w4">
                        <div class="zongshijian"><h1 class="banciname">
                            {{ calculateDuration(train.departureTime, train.arrivalTime) }}</h1></div>
                    </div>

                    <!-- 第五列：参考价 - 显示所有席别类型和价格 -->
                    <div class="w5" style="margin-left: -50px; min-width: 180px;">
                        <div class="cankaojia" v-for="ticket in train.tickets" :key="ticket.ticketId"
                             style="display: block; margin-bottom: 5px;">
                            <span class="jiaqian">
                                <span>{{ getCarriageTypeName(ticket.carriageType) }}</span>
                                <font>￥<b class="piaozi1">{{ ticket.ticketPrice }}</b></font>
                            </span>
                        </div>
                    </div>

                    <!-- 第六列：剩余票数 - 显示所有席别的余票状态 -->
                    <div class="w6" style="margin-left: -100px;min-width: 120px;">
                        <div class="shengyu" v-for="ticket in train.tickets" :key="ticket.ticketId"
                             style="display: block; margin-bottom: 5px;">
                            <span v-if="ticket.remainingTickets === 0 && ticket.ticket_status === 1">已售罄</span>
                            <span v-if="ticket.ticket_status === 0">停售</span>
                            <span v-if="ticket.remainingTickets > 0 && ticket.ticket_status === 1">余<b
                                    class="shengyu1">{{ ticket.remainingTickets }}</b>张</span>
                        </div>
                    </div>

                    <!-- 第七列：票务预定 - 显示所有席别的预定按钮 -->
                    <div class="w7" style="margin-left: 50px; min-width: 100px;">
                        <div v-for="ticket in train.tickets" :key="ticket.ticketId"
                             style="display: block; margin-bottom: 5px;">
                            <a v-if="ticket.remainingTickets > 0 && ticket.ticket_status === 1" class="qp_btn1"
                               href="javascript:void(0);" canthese="True" @click="buyTicket(user, ticket)">预定</a>
                            <a v-else class="qp_btn1" href="javascript:void(0);" canthese="True">无法预定</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 表单保存该列车数据 -->
        <form action="/view/ticketing/confirmPassenger" method="post" id="Form01">
            <!--隐藏域-->
            <input type="hidden" id="trainInfo" name="trainInfo" :value="selectedTrainInfo">
        </form>
    </div>

</div>

<div id="footer" class="mt-20"></div>

<script type="text/javascript">
    // 动态加载header和footer
    $(document).ready(function () {
        // 加载header
        $.ajax({
            url: '/home/header.html',
            type: 'GET',
            success: function (response) {
                $('#header').html(response);
            },
            error: function () {
                console.log('加载header失败');
            }
        });

        // 加载footer
        $.ajax({
            url: '/home/footer.html',
            type: 'GET',
            success: function (response) {
                $('#footer').html(response);
            },
            error: function () {
                console.log('加载footer失败');
            }
        });
    });

    // Vue 实例
    new Vue({
        el: '#app',
        data() {
            return {
                searchForm: {},
                startCity: '',
                endCity: '',
                goTime: '',
                displayDate: '',
                from: '',
                to: '',
                tos: '',
                changeFlag: '',
                changeFlag_num: '',
                time: 0,
                trainList: [], // 原始车票数据列表
                groupedTrainList: [], // 按车次合并后的车票数据
                user: '',
                showDateModal: false,
                selectedDate: '', // 修改为selectedDate以避免与方法名冲突
                showNoResult: false,
                showNoResultMessage: '暂无符合条件的车票',
                dateList: [], // 添加dateList字段用于存储日期列表
                currentDateIndex: 0, // 添加currentDateIndex字段用于跟踪当前选中的日期索引
                // 添加缺失的属性以解决Vue警告
                hub: null,
                validates: {},
                selectedTrainInfo: '',
                laydateInstance: null, // 添加laydateInstance字段用于保存laydate实例
                clickedTrain: null  // 当前点击选中的车次信息
            }
        },
        mounted() {
            // 初始化页面数据
            this.initializePage();
            // 设置当前时间更新
            this.startTimeUpdate();
            // 初始化日期选择器
            this.initDatePickers();
            // 加载用户信息
            this.user = localStorage.getItem("USER_ID");
        },
        methods: {
            // 格式化日期时间显示
            formatDateTime(dateTimeStr) {
                if (!dateTimeStr) return '';
                // 检查是否为纯时间字符串格式 (HH:mm:ss)
                if (dateTimeStr.match(/^\d{2}:\d{2}:\d{2}$/)) {
                    // 如果是纯时间格式，直接返回小时和分钟
                    return dateTimeStr.substring(0, 5);
                }
                // 否则按日期对象处理
                const date = new Date(dateTimeStr);
                return date.getHours().toString().padStart(2, '0') + ':' + date.getMinutes().toString().padStart(2, '0');
            },


            // 计算行程时长
            calculateDuration(departureTime, arrivalTime) {
                if (!departureTime || !arrivalTime) return '';
                const start = new Date(departureTime);
                const end = new Date(arrivalTime);
                const diff = end - start;
                const hours = Math.floor(diff / (1000 * 60 * 60));
                const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                return hours + '小时' + minutes + '分钟';
            },

            // 按车次合并相同车次的车票
            mergeTrainTickets(tickets) {
                // 创建一个Map用于按车次分组
                const trainMap = new Map();

                // 遍历所有车票，按车次分组
                tickets.forEach(ticket => {
                    const trainNumber = ticket.trainNumberId;

                    if (!trainMap.has(trainNumber)) {
                        // 如果是新车次，创建一个新的车次对象
                        trainMap.set(trainNumber, {
                            trainNumberId: trainNumber,
                            departureTime: ticket.departureTime,
                            arrivalTime: ticket.arrivalTime,
                            startStationId: ticket.startStationId,
                            arrivalStationId: ticket.arrivalStationId,
                            tickets: [ticket] // 将当前车票作为该车次的第一张票
                        });
                    } else {
                        // 如果车次已存在，将当前车票添加到该车次的车票列表中
                        const trainInfo = trainMap.get(trainNumber);
                        trainInfo.tickets.push(ticket);
                    }
                });

                // 将Map转换为数组并返回
                return Array.from(trainMap.values());
            },

            // 根据车厢类型数字获取车厢类型名称
            // 根据车厢类型数字获取车厢类型名称
            getCarriageTypeName(carriageType) {
                const typeMap = {
                    1: '一等座',
                    2: '二等座',
                    3: '商务座',
                    4: '硬座',
                    5: '硬卧',
                    6: '软卧'
                };
                return typeMap[carriageType] || '其他';
            },
            // 初始化页面数据
            initializePage() {
                // 从localStorage读取搜索参数
                this.loadSearchParams();

                // 检查URL参数（URL参数优先级高于localStorage）
                this.checkUrlParams();

                // 初始化日期列表
                this.initDateList();

                // 检查是否可以搜索列车
                this.checkAndSearchTrains();
            },

            // 检查URL参数
            checkUrlParams() {
                const urlParams = new URLSearchParams(window.location.search);
                const changeFlag = urlParams.get('changeFlag');
                const changeFlagNum = urlParams.get('changeFlag_num');

                // 获取index页面传递的参数
                const startCity = urlParams.get('startCity') || urlParams.get('startStation');
                const endCity = urlParams.get('endCity') || urlParams.get('endStation');
                const goDate = urlParams.get('goDate');

                if (changeFlagNum) {
                    this.changeFlag_num = changeFlagNum;
                    this.time = parseInt(changeFlagNum);
                }

                if (changeFlag) {
                    this.changeFlag = changeFlag;
                }

                // 设置从index页面传递的参数
                if (startCity) {
                    this.startCity = startCity;
                    this.from = startCity;
                }

                if (endCity) {
                    this.endCity = endCity;
                    this.to = endCity;
                    this.tos = endCity;
                }

                if (goDate) {
                    this.goTime = goDate;
                    this.displayDate = goDate;
                }
            },


            // 检查是否可以开始搜索列车
            checkAndSearchTrains() {
                // 如果有城市信息和日期信息，则开始搜索
                if (this.startCity && this.endCity && this.goTime) {
                    this.searchTrains();
                }
            },


            // 从本地存储加载搜索参数
            loadSearchParams() {
                const savedParams = localStorage.getItem('searchParams');

                if (savedParams) {
                    try {
                        const searchParams = JSON.parse(savedParams);

                        // 兼容两种字段名：startCity和startStation
                        if (searchParams.startCity || searchParams.startStation) {
                            this.startCity = searchParams.startCity || searchParams.startStation;
                            this.from = searchParams.startCity || searchParams.startStation;
                        }

                        // 兼容两种字段名：endCity和endStation
                        if (searchParams.endCity || searchParams.endStation) {
                            this.endCity = searchParams.endCity || searchParams.endStation;
                            this.to = searchParams.endCity || searchParams.endStation;
                            this.tos = searchParams.endCity || searchParams.endStation;
                        }


                        if (searchParams.goTime) {
                            this.goTime = searchParams.goTime;
                            this.displayDate = searchParams.goTime;
                        }
                    } catch (error) {
                        console.error('加载保存的搜索参数失败:', error);
                    }
                }
            },

            // 保存搜索参数到本地存储
            saveSearchParams() {
                const searchParams = {
                    startCity: this.startCity,
                    endCity: this.endCity,

                    goTime: this.goTime
                };

                localStorage.setItem('searchParams', JSON.stringify(searchParams));
            },

            // 初始化日期列表
            initDateList() {
                this.dateList = [];
                const today = new Date();
                const now1 = new Date(today.getTime() + (this.time * 24 * 60 * 60 * 1000));

                for (let i = 0; i < 7; i++) {
                    const date = new Date(now1.getTime() + i * 24 * 3600 * 1000);
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    const week = ['日', '一', '二', '三', '四', '五', '六'][date.getDay()];

                    this.dateList.push({
                        date: `${month}-${day}`,
                        day: `星期${week}`,
                        fullDate: `${date.getFullYear()}-${month}-${day}`
                    });
                }

                // 检查是否有选中的日期
                if (this.goTime) {
                    const goDate = this.goTime;
                    const index = this.dateList.findIndex(d => d.fullDate === goDate);
                    if (index !== -1) {
                        this.currentDateIndex = index;
                    }
                }
            },

            // 格式化日期为YYYY-MM-DD
            formatDate(date) {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            },

            // 开始时间更新
            startTimeUpdate() {
                this.updateDateTime();
                setInterval(() => this.updateDateTime(), 1000);
            },

            // 更新当前时间
            updateDateTime() {
                this.currentTime = new Date().toLocaleString();
            },

            // 交换城市
            exchangeCities() {
                // 交换城市信息
                const tempCity = this.startCity;
                this.startCity = this.endCity;
                this.endCity = tempCity;

                // 更新显示的城市名称
                const tempFrom = this.from;
                this.from = this.to;
                this.to = tempFrom;

                // 更新站点列表
                const tempStations = this.startCityStations;
                this.startCityStations = this.endCityStations;
                this.endCityStations = tempStations;

                // 保存搜索参数
                this.saveSearchParams();
            },

            // 选择日期
            selectDate(index) {
                this.currentDateIndex = index;
                const selectedDate = this.dateList[index].fullDate;
                this.goTime = selectedDate;
                this.displayDate = selectedDate;
                this.changeFlag = 'default';
                this.saveSearchParams();
                // 这里应该提交表单或调用搜索函数
                this.searchTrains();
            },

            // 日期右按钮点击
            CanlenderRightButtonClick() {
                this.changeFlag = 'next';
                this.saveSearchParams();
                // 提交表单
                this.submitForm();
            },

            // 日期左按钮点击
            CanlenderLeftButtonClick() {
                this.changeFlag = 'previous';
                this.saveSearchParams();
                // 提交表单
                this.submitForm();
            },

            // 提交表单
            submitForm() {
                // 这里可以构造表单数据并提交
                const form = document.getElementById('form');
                const url = '/view/ticketing/list';
                const formData = new URLSearchParams();
                formData.append('start_station', this.startCity);
                formData.append('end_station', this.endCity);
                formData.append('go_time', this.goTime);
                formData.append('changeFlag', this.changeFlag);
                formData.append('changeFlag_num', this.changeFlag_num);

                // 实际应用中可以使用axios提交
                window.location.href = `${url}?${formData.toString()}`;
            },

            // 表单值变化处理
            changeValue() {
                this.goTime = this.displayDate;
                // 查找对应的日期索引并更新currentDateIndex
                const index = this.dateList.findIndex(date => date.fullDate === this.displayDate);
                if (index !== -1) {
                    this.currentDateIndex = index;
                }
                this.saveSearchParams();
                this.searchTrains();
                return true;
            },

            // 搜索列车
            searchTrains() {
                // 打印当前参数信息，便于调试
                console.log('发送请求参数:', {
                    startCity: this.startCity,
                    endCity: this.endCity,
                    goDate: this.goTime
                });

                // 直接将城市信息和日期信息发送给后端
                axios.get('/home/ticket_manage/tickets', {
                    params: {
                        startCity: this.startCity,
                        endCity: this.endCity,
                        goDate: this.goTime
                    }
                })
                    .then(response => {
                        console.log('查询车票成功，返回数据:', response.data);
                        // 处理返回的ResponseResult对象，获取其中的data字段
                        const ticketList = response.data.data || [];
                        // 处理返回的车票数据，确保字段名称匹配
                        this.trainList = ticketList.map(ticket => ({
                            ticketId: ticket.ticketId || ticket.ticket_id,
                            trainNumberId: ticket.trainNumberId || ticket.train_number_id,
                            carriageType: ticket.carriageType || ticket.carriage_type,
                            startStationId: ticket.startStationId || ticket.start_station_id,
                            arrivalStationId: ticket.arrivalStationId || ticket.arrival_station_id,
                            departureTime: ticket.departureTime || ticket.departure_time,
                            arrivalTime: ticket.arrivalTime || ticket.arrival_time,
                            ticketPrice: ticket.ticketPrice || ticket.ticket_price,
                            totalTickets: ticket.totalTickets || ticket.total_tickets,
                            remainingTickets: ticket.remainingTickets || ticket.remaining_tickets,
                            // 如果后端返回了ticket_status字段则保留，否则默认设置为1（可预订）
                            ticket_status: ticket.ticket_status !== undefined ? ticket.ticket_status : 1
                        })) || [];

                        // 按车次合并相同车次的车票
                        this.groupedTrainList = this.mergeTrainTickets(this.trainList);

                        // 保存搜索参数
                        this.saveSearchParams();
                        // 处理无结果的情况
                        this.showNoResult = this.groupedTrainList.length === 0;
                    })
                    .catch(error => {
                        console.error('查询车票信息失败:', error);
                        alert('查询车票信息失败，请稍后再试');
                        this.trainList = []; // 清空车票列表
                        this.showNoResult = true;
                    });
            },
            // 购买车票
            buyTicket(user, ticket) {
                // 判断当前用户是否处于登录状态
                if (user != null) {
                    // 将选中的车票信息存储在localStorage中
                    localStorage.setItem('selectedTrain', JSON.stringify({
                        departure_date: this.goTime,
                        train_number: ticket.trainNumberId,
                        start_station: this.startCity,
                        start_time: ticket.departureTime,
                        end_station: this.endCity,
                        arrive_time: ticket.arrivalTime,
                        id: ticket.ticketId,
                        seatInfoEntityList: [{
                            seat_type_id: ticket.carriageType,
                            price: ticket.ticketPrice,
                            remain_nums: ticket.remainingTickets,
                            seatType: {
                                seat_type_name: this.getCarriageTypeName(ticket.carriageType)
                            }
                        }]
                    }));
                    // 保存当前搜索信息，方便返回时恢复
                    this.saveSearchParams();
                    // 跳转到选择乘车人页面
                    window.location.href = '/home/order/choose_passenger.html';
                } else {
                    let login = window.confirm("您当前还没有登录，是否去登录！");
                    if (login) {
                        // 保存当前车票信息，登录后可以直接购买
                        localStorage.setItem('tempSelectedTicket', JSON.stringify(ticket));
                        window.location.href = "/home/login.html";
                    }
                }
            },


            // 初始化日期选择器
            initDatePickers() {
                // 这里应该初始化日期选择器
                // 由于ECalendar和laydate需要在DOM加载完成后初始化
                setTimeout(() => {
                    try {
                        // 优先使用laydate
                        if (window.laydate && typeof laydate.render === 'function') {
                            // 初始化laydate
                            const laydateObj = laydate.render({
                                elem: "#ECalendar_case1",
                                type: 'date',
                                format: 'yyyy-MM-dd',
                                done: (value, date, endDate) => {
                                    this.goTime = value;
                                    this.displayDate = value;
                                    this.saveSearchParams();
                                    console.log('日期选择器选择日期后直接搜索:', value);
                                }
                            });
                            // 保存laydate实例
                            this.laydateInstance = laydateObj;
                        } else if (window.laydate) {
                            // 兼容旧版本的laydate
                            laydate({
                                elem: "#ECalendar_case1",
                                choose: (dates) => {
                                    this.goTime = dates;
                                    this.displayDate = dates;
                                    this.saveSearchParams();
                                    console.log('旧版日期选择器选择日期后:', dates);
                                }
                            });
                        } else if ($ && $.fn.ECalendar) {
                            // 如果laydate不可用，使用ECalendar
                            $("#ECalendar_case1").ECalendar({
                                type: "date",
                                skin: "#009f95",
                                name: "time1",
                                offset: [0, 2],
                                callback: (value) => {
                                    this.goTime = value;
                                    this.displayDate = value;
                                    this.saveSearchParams();
                                    console.log('ECalendar选择日期后:', value);
                                }
                            });
                        } else {
                            console.log('没有可用的日期选择器库');
                            // 如果没有日期选择器库，确保输入框仍然可以手动输入
                            const dateInput = document.getElementById('ECalendar_case1');
                            if (dateInput) {
                                dateInput.removeAttribute('readonly');
                                dateInput.style.cursor = 'text';
                                dateInput.addEventListener('change', () => {
                                    this.goTime = dateInput.value;
                                    this.displayDate = dateInput.value;
                                    this.saveSearchParams();
                                    console.log('手动输入日期后:', dateInput.value);
                                });
                            }
                        }
                    } catch (error) {
                        console.error('初始化日期选择器失败:', error);
                        // 出错时确保输入框仍然可以手动输入
                        const dateInput = document.getElementById('ECalendar_case1');
                        if (dateInput) {
                            dateInput.removeAttribute('readonly');
                            dateInput.style.cursor = 'text';
                        }
                    }
                }, 200);
            },
            // 显示日期选择器
            showDatePicker() {
                try {
                    if (this.laydateInstance) {
                        if (typeof this.laydateInstance.hint === 'function') {
                            this.laydateInstance.hint(); // 调用laydate的hint方法显示日期选择器
                        } else {
                            // 兼容旧版本的laydate
                            const dateInput = document.getElementById('ECalendar_case1');
                            if (dateInput) {
                                dateInput.focus();
                            }
                        }
                    }
                } catch (error) {
                    console.error('显示日期选择器失败:', error);
                }
            },

            // 显示经停站信息（已改为点击显示，保留方法名兼容）
            showStations(train) {
                // 点击显示，此方法保留但不执行任何操作                // 如果没有点击选中的车次或点击的不是当前车次，则显示悬浮效果
                if (!this.clickedTrain || this.clickedTrain.trainNumberId !== train.trainNumberId) {
                    // 深拷贝当前车次信息，避免修改原数据
                    this.hoveredTrain = JSON.parse(JSON.stringify(train));

                    // 悬浮时不主动请求经停站数据，只显示已有的数据（如果有）
                    // 经停站数据只在点击车次时获取
                }
            },

            // 隐藏悬浮的经停站信息
            hideStations() {
                // 如果没有点击选中的车次，则隐藏悬浮效果
                if (!this.clickedTrain) {
                    this.hoveredTrain = null;
                }
            },

            // 切换点击状态的经停站信息显示
            toggleStations(train) {
                // 如果点击的是当前选中的车次，则关闭它
                if (this.clickedTrain && this.clickedTrain.trainNumberId === train.trainNumberId) {
                    this.closeStations();
                } else {
                    // 否则显示新选中的车次
                    this.clickedTrain = JSON.parse(JSON.stringify(train));

                    // 确保hoveredTrain也更新
                    this.hoveredTrain = this.clickedTrain;

                    // 检查是否已有经停站数据
                    if (!this.clickedTrain.stations) {
                        // 模拟获取经停站数据
                        this.getTrainStations(train.trainNumberId);
                    }

                    // 添加点击外部关闭的监听
                    this.addClickOutsideListener();
                }
            },

            // 关闭所有经停站显示
            closeStations() {
                this.clickedTrain = null;

                // 移除点击外部关闭的监听
                this.removeClickOutsideListener();
            },

            // 获取车次经停站信息
            getTrainStations(trainNumberId) {
                // 使用axios请求获取实际经停站数据
                // 确保URL路径正确
                const url = `/admin/train_number/getTrainStations/${trainNumberId}`;
                console.log('请求经停站信息:', url);

                axios.get(url)
                    .then(response => {
                        console.log('获取经停站成功:', response.data);
                        // 处理返回的经停站数据，注意实际数据在response.data.data中
                        const stations = response.data.data || [];
                        console.log(`获取到${stations.length}个经停站`);

                        // 确保每个站点都有stationOrder字段
                        stations.forEach((station, index) => {
                            station.stationOrder = index + 1;
                        });

                        // 添加调试日志，检查终点站数据
                        if (stations.length > 0) {
                            const lastStation = stations[stations.length - 1];
                            console.log('终点站信息:', lastStation.stationName, '到达时间:', lastStation.arriveTime);

                            // 确保终点站有到达时间，如果没有则从车次主数据中获取
                            if (!lastStation.arriveTime && this.clickedTrain && this.clickedTrain.arrivalTime) {
                                console.log('终点站到达时间缺失，从车次主数据补充:', this.clickedTrain.arrivalTime);
                                lastStation.arriveTime = this.clickedTrain.arrivalTime;
                            } else if (!lastStation.arriveTime) {
                                // 如果车次主数据也没有，则设置一个默认值
                                lastStation.arriveTime = '暂无到达时间';
                                console.log('终点站到达时间缺失，设置默认值');
                            }
                        }

                        // 只更新clickedTrain的经停站数据
                        if (this.clickedTrain && this.clickedTrain.trainNumberId === trainNumberId) {
                            console.log('更新clickedTrain的经停站数据');
                            // 使用Vue.set确保响应式更新
                            this.$set(this.clickedTrain, 'stations', stations);
                        } else {
                            console.log('无法更新经停站数据，目标车次不存在或ID不匹配');
                        }
                    })
                    .catch(error => {
                        console.error('获取经停站信息失败:', error);
                        // 出错时使用模拟数据作为备用
                        const mockStations = this.generateMockStations(trainNumberId);
                        console.log('使用模拟数据:', mockStations);

                        // 根据调用类型更新相应的数据
                        if (type === 'click' && this.clickedTrain && this.clickedTrain.trainNumberId === trainNumberId) {
                            this.clickedTrain.stations = mockStations;
                        } else if (type === 'hover' && this.hoveredTrain && this.hoveredTrain.trainNumberId === trainNumberId) {
                            this.hoveredTrain.stations = mockStations;
                        }
                    });
            },

            // 添加点击外部关闭的监听
            addClickOutsideListener() {
                // 先移除已有的监听器，避免重复添加
                this.removeClickOutsideListener();

                // 添加新的监听器
                this.clickOutsideHandler = (event) => {
                    // 检查点击的是否是车次区域或浮窗区域
                    const isCheciElement = event.target.closest('.checi');
                    if (!isCheciElement) {
                        this.closeStations();
                    }
                };

                document.addEventListener('click', this.clickOutsideHandler);
            },

            // 移除点击外部关闭的监听
            removeClickOutsideListener() {
                if (this.clickOutsideHandler) {
                    document.removeEventListener('click', this.clickOutsideHandler);
                    this.clickOutsideHandler = null;
                }
            },

            // 生成模拟经停站数据
            generateMockStations(trainNumberId) {
                // 基于车次号生成一些模拟的经停站数据
                const stations = [];
                const stationCount = Math.floor(Math.random() * 5) + 3; // 3-7个经停站
                const startHour = 8;

                // 模拟起始站
                stations.push({
                    stationName: this.startCity,
                    departureTime: new Date(this.goTime + ' ' + startHour + ':00').toISOString()
                });

                // 模拟中间站
                for (let i = 1; i < stationCount - 1; i++) {
                    const hour = startHour + i;
                    stations.push({
                        stationName: '车站' + i,
                        arrivalTime: new Date(this.goTime + ' ' + hour + ':15').toISOString(),
                        departureTime: new Date(this.goTime + ' ' + hour + ':20').toISOString()
                    });
                }

                // 模拟终点站
                stations.push({
                    stationName: this.endCity,
                    arrivalTime: new Date(this.goTime + ' ' + (startHour + stationCount) + ':00').toISOString()
                });

                return stations;
            }
        }
    });
</script>

<script type="text/javascript" src='/home/js/LAB.js'></script>
<script type="text/javascript">
    var uid = '';
    var IsTieYou = '0';
    var flightFlag = '1';
    var tychannel = ''; //铁友channel
    var SEARCH_CATE_LIST_No = ['01'];
    var webResourcePath = "http://webresource.ctrip.com/ResTrainOnline/R2/TrainBooking";
    var noticeContent = "";
    var releaseNo = "2017_10_11_15_10_25";
    var newFightTicket = "1";
    var searchMaxDate = '2017-11-24';
    $LAB.script({
        src: 'js/cQuery_110421.js',
        charset: "utf-8"
    }).wait().script(
        {
            src: webResourcePath + "/JS/ui2_train.min.js?"
                + releaseNo + ".js",
            charset: "utf-8"
        }).wait().script(
        {
            src: webResourcePath + "/JS/calendar.min.js?"
                + releaseNo + ".js",
            charset: "utf-8"
        }).wait().script(
        {
            src: webResourcePath + "/JS/ol_hotel.min.js?"
                + releaseNo + ".js",
            charset: "utf-8"
        }).wait().script(
        {
            src: webResourcePath + "/JS/ol_search.min.js?"
                + releaseNo + ".js",
            charset: "utf-8"
        }).wait()
</script>
<script type="text/javascript" src="/home/js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="/home/js/city-data.js"></script>
<script type="text/javascript" src="/home/js/hzw-city-picker.min.js"></script>
<script type="text/javascript" src="/home/js/jquery.min.js"></script>
<script type="text/javascript" src="/home/js/Ecalendar.jquery.min.js"></script>
<script src="/home/js/plugins/layer/laydate/laydate.js"></script>
<script src="/home/js/jquery-3.5.1.js" type="text/javascript" charset="utf-8"></script>
<script src="/home/js/public.js" type="text/javascript" charset="utf-8"></script>
<script src="/home/js/user.js" type="text/javascript" charset="utf-8"></script>

</body>
</html>
